<template>
    <div>

        <el-card>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-button type="primary" @click="newCp"
                        >添加商品</el-button
                    >
                </el-col>
            </el-row>
            <el-table :data="cpList" border stripe>
                <el-table-column
                    label="id"
                    prop="id"
                    width="60"
                ></el-table-column>
                <el-table-column label="logo">
                    <template v-if="scope.row.logo" slot-scope="scope">
                        <img
                            :src="
                                imgBaseUrl +
                                scope.row.logo +
                                '?iopcmd=thumbnail&type=4&width=150'
                            "
                            alt=""
                            class="logo_pic"
                        />
                    </template>
                </el-table-column>

                <el-table-column label="管理对象" prop="productName" />
                <el-table-column label="类型">
                    <template slot-scope="scope">
                      <span v-if="scope.row.flag==='djth'">当季特惠</span>
                      <span v-if="scope.row.flag==='elec'">抵用券</span>
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.status"
                            active-value="Y"
                            inactive-value="N"
                            @change="
                                switchCpStatus(scope.row.id, scope.row.status)
                            "
                        ></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="排序">
                    <template slot-scope="scope">
                        <el-input
                            v-model="scope.row.sortNum"
                            placeholder="请输入内容"
                            @change="
                                setSortNum(scope.row.id, scope.row.sortNum)
                            "
                        ></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            @click="editCp(scope.row)"
                        ></el-button>
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            @click="deleteCp(scope.row.id)"
                        ></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pagenum"
                :page-sizes="[5, 10, 20]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            >
            </el-pagination>
        </el-card>

        <!-- 添加广告的对话框 -->
        <el-dialog
            title="添加商品"
            :visible.sync="addBannerVisible"
            width="50%"
            @close="addDialogClosed"
        >
            <el-form
                :model="addForm"
                :rules="addFormRules"
                ref="addAdForm"
                label-width="120px"
                class="demo-ruleForm"
            >
                <el-form-item>
                    <el-select label="类型" prop="flag" v-model="addForm.flag"  style="wdith:120px;">
                            <el-option
                                key="djyh"
                                label="当季特惠"
                                value="djth">
                            </el-option>
                            <el-option
                                key="elec"
                                label="抵用券"
                                value="elec">
                            </el-option>
                        </el-select>
                </el-form-item>
                <el-form-item label="商品名称" prop="productName">
                    <el-autocomplete
                        v-model="addForm.productName"
                        :fetch-suggestions="queryRelateItem"
                        placeholder="请输入内容"
                        @select="selectRelateName"
                    ></el-autocomplete>
                </el-form-item>

                <el-form-item label="logo" prop="logo">
                    <div class="form_row">
                        <img
                            v-for="(item, index) in uploadList"
                            :src="imgBaseUrl + item"
                            :key="index"
                            class="upload_img"
                            alt=""
                        />
                        <el-upload
                            class="upload-demo"
                            :limit="10"
                            :action="actionPath"
                            :on-success="handleImgSuccess"
                            :on-remove="handleImgRemove"
                            :on-exceed="handleExceed"
                            :show-file-list="false"
                            list-type="picture-card"
                        >
                            <img
                                class="el-upload-list__item-thumbnail"
                                :src="addForm.logo"
                                alt=""
                            />
                            <i slot="default" class="el-icon-plus"></i>
                        </el-upload>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addBannerVisible = false">取 消</el-button>
                <el-button type="primary" @click="addCp">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Api from "@/api/Api.js";
export default {
    data() {
        return {
            imgBaseUrl: this.$global.imgBaseUrl,
            actionPath: process.env.VUE_APP_BASE_API + "api/upload/image",
            fileList: [],
            addBannerVisible: false,
            cpList: [],
            pagenum: 1, // 页码
            pagesize: 10, // 页大小
            total: 0,
            addForm: {
                productName: "",
                logo: "",
                flag:'djth',
                productId: "",
            },
            addFormRules: {
                productName: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "change",
                    },
                ],
                logo: [
                    {
                        required: true,
                        message: "请上传图片",
                        trigger: "change",
                    },
                ],
            },
            productName: "",
            dialogVisible: false,
            dialogImageUrl: "",
            logoList: [],
            uploadList: [],
            disabled: false,
        };
    },
    watch: {
        logoList: {
            handler(val, oldVal) {
                console.log(val);
            },
            deep: true,
        },
    },
    components: {},
    created() {
        this.getCpList();
    },
    methods: {
        // 打开添加广告的弹窗
        newCp() {
            this.addForm = {
                productName: "",
                logo: "",
                productId: ""
            };
            this.uploadList = [];
            this.addBannerVisible = true;
        },
        // 获取广告列表
        getCpList() {
            Api.getCommendProductList({
                pagenum: this.pagenum,
                pagesize: this.pagesize,
            }).then((res) => {
                this.cpList = res.data.commendProductList;
                this.total = res.data.total;
                this.pagenum = res.data.pagenum;
            });
        },
        addCp() {
            this.$refs["addAdForm"].validate((valid) => {
                if (valid) {
                    let data = this.addForm;
                    Api.saveOrUpdateCommendProduct(data).then((res) => {
                        if (res.success) {
                            this.addBannerVisible = false;
                            this.getCpList();
                        }
                    });
                    console.log(data);
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        // 查询管理对象
        queryRelateItem(queryString, cb) {
            Api.searchCommendProductList({
                name: this.addForm.productName,
                pagenum: 0,
                pagesize: 10
            }).then((res) => {
                let arr = [];
                for (let i of res.data.searchList) {
                    let obj = { value: "", id: "" };
                    obj.value = i.name;
                    obj.id = i.id;
                    arr.push(obj);
                }
                cb(arr);
            });
        },
        // 监听pagesize改变的事件
        handleSizeChange(pagesize) {
            this.pagesize = pagesize;
            this.getCpList();
        },
        // 监听pagenum的事件
        handleCurrentChange(pagenum) {
            this.pagenum = pagenum;
            this.getCpList();
        },
        // 监听添加用户对话框的关闭事件
        addDialogClosed() {
        },
        selectRelateName(item) {
            console.log(item);
            this.addForm.productId = item.id;
        },
        handleImgSuccess(res, file, logoList) {
            this.addForm.logo = res.data;
            let uploadList = [];
            uploadList.push(res.data);
            this.uploadList = uploadList;
        },
        handleImgRemove(res, file) {
            console.log(res, file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 1 个文件`);
        },
        switchCpStatus(id, status) {
            console.log(status);
            Api.saveCommendProductStatus({
                id: id,
                status: status,
            }).then((res) => {
                if (res.success) {
                    this.getCpList();
                }
            });
        },
        editCp(info) {
            this.addForm = JSON.parse(JSON.stringify(info));
            this.addBannerVisible = true;
            let uploadList = [];
            uploadList.push(info.logo);
            this.uploadList = uploadList;
        },
        deleteCp(id) {
            this.$confirm("确认删除？")
                .then((_) => {
                    Api.deleteCommendProduct({
                        id: id,
                    }).then((res) => {
                        if (res.success) {
                            this.getCpList();
                        }
                    });
                })
                .catch((_) => {});
        },
        // 修改广告排序
        setSortNum(id, sortNum) {
            console.log(id, sortNum);
            Api.saveCommendProductSortNum({
                id: id,
                sortNum: sortNum,
            }).then((res) => {
                if (res.success) {
                    this.getCpList();
                }
            });
        },
    },
};
</script>
<style lang="less">
.logo_pic {
    max-width: 150px;
}
.form_row {
    display: flex;
}
.el-upload-list__item-thumbnail {
    object-fit: cover;
}
.upload_img {
    width: 148px;
    height: 148px;
    object-fit: cover;
    border-radius: 6px;
    margin-right: 20px;
}
</style>
